package Dome429;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

//发送方
public class UdpSender {

    public static void main(String[] args) {
        //声明数据包对象
        DatagramPacket dp = null;
        //声明数据包套接字对象
        DatagramSocket ds = null;
        //创建Scanner对象
        Scanner input = new Scanner(System.in);
        try {
            ds = new DatagramSocket();

            byte[] data = new byte[1024];

            while(true){
                String mess = input.nextLine();
                byte[] buf = mess.getBytes();
                //将数据封装成数据包
                dp = new DatagramPacket(buf,buf.length, InetAddress.getByName("localhost"),8989);
                //将数据包发送给服务器
                ds.send(dp);


                //接收服务器响应
                //准备空的数据包
                dp = new DatagramPacket(data,data.length);
                //接收数据包
                ds.receive(dp);
                //将数据包解析为字符串
                mess = new String(dp.getData(),0,dp.getLength());
                System.out.println("服务器响应为：" + mess);

            }
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            ds.close();
        }
    }

}
